/*================================================================
*   Copyright (C) 2023 baichao All rights reserved.
*
*   文件名称：main_posix.cpp
*   创 建 者：baichao
*   创建日期：2023年12月12日
*   描    述：
*
================================================================*/

#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <limits.h>
#include <errno.h>

int mkdir_p(const char *dir_path, mode_t mode)
{
    char _dir_path[PATH_MAX];
    char *p = NULL;
    size_t len;

    // Copy the input string to a temporary buffer
    len = strlen(dir_path);
    if (len >= sizeof(_dir_path))
    {
        fprintf(stderr, "mkdir_p: path too long\n");
        return -1;
    }
    strcpy(_dir_path, dir_path);

    // Iterate over each component of the directory path
    for (p = _dir_path + (*_dir_path == '/'); *p; p++)
    {
        if (*p == '/')
        {
            *p = '\0';

            // Attempt to create the current directory
            if (mkdir(_dir_path, mode) != 0 && errno != EEXIST)
            {
                fprintf(stderr, "mkdir_p: %s: %s\n", _dir_path, strerror(errno));
                return -1;
            }

            *p = '/';
        }
    }

    // Attempt to create the final directory
    if (mkdir(_dir_path, mode) != 0 && errno != EEXIST)
    {
        fprintf(stderr, "mkdir_p: %s: %s\n", _dir_path, strerror(errno));
        return -1;
    }

    return 0;
}

int create_directory(const char *dir_path)
{
    struct stat info;

    // Check if the directory already exists
    if (stat(dir_path, &info) == 0 && S_ISDIR(info.st_mode))
    {
        printf("Directory already exists: %s\n", dir_path);
        return 1;
    }

    // Attempt to create the directory
    if (mkdir_p(dir_path, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == 0)
    {
        printf("Directory created successfully: %s\n", dir_path);
        return 1;
    }
    else
    {
        perror("Failed to create directory");
        return 0;
    }
}

int main()
{
    create_directory("/home/baichao/code/c++/cpp_test/folder/data/data1");
}